/*
 * @Author       : Hejh(3010733382@qq.com)
 * @Version      : V1.0
 * @Date         : 2024-01-31 11:03:31
 * @Description  : 动态导入背景的hooks，随机生成一张背景图
 */

export const userBg = () => {
  const curBgUrl = ref('url(/src/assets/images/1.jpg)')
  const loading = ref(true)

  const loadBg = () => {
    const random = Math.floor(Math.random() * 13) + 1
    const url = `/src/assets/images/${random}.jpg`
    import(/* @vite-ignore */ url).then((image) => {
      curBgUrl.value = `url(${image.default})`
    })

    const image = new Image()
    image.src = url
    image.onload = hideLoading
    image.onerror = hideLoading
  }

  const hideLoading = () => {
    setTimeout(() => {
      loading.value = false
    })
  }

  onMounted(() => {
    loadBg()
  })

  return {
    curBgUrl,
    loading
  }
}
